<template>
  <a-spin :spinning="spinning">
    <div class="content" ref="content">
      <div class="canvas" ref="canvas" :style="{height:height}"></div>
    </div>
  </a-spin>
</template>

<script>

  import { getAction } from '@/api/manage'
  import {
    NavigatedViewer
  } from '@yuncheng/ych-bpm-designer'
  import YchConstant from "@/api/YchConstant";

  export default {
    name: 'BpmPic',
    props: {
      processInstanceId: {
        type: String,
        default: null
      },
      processDefId: {
        type: String,
        default: null
      },
      refreshFlg: {
        type: Number,
        default: 0
      }
    },
    data () {
      return {
        spinning: false,
        viewer: null,
        container: null,
        canvas: null,
        histActivity: {},
        currActivity: {},
        url: {
          getBpmPic: YchConstant.PREFIX_BPM + '/bpm-front/displayRest/getBpmPic/v1',
        },
        height: '100px'
      }
    },
    methods: {
      openDiagram (xml) {
        const that = this
        this.viewer.importXML(xml, function (err) {
          if (err) {
            that.messageUtil.warning(err.message)
          }
        })
      },
      open () {
        window.getHistActivity = this.getHistActivity
        window.getCurrActivity = this.getCurrActivity
        if (!this.processDefId) {
          return
        }
        const that = this
        that.spinning = true
        getAction(this.url.getBpmPic, {
          processDefId: this.processDefId,
          processInstanceId: this.processInstanceId
        }).then((res) => {
          if (res.success) {
            that.histActivity = res.result.histActivity
            that.currActivity = res.result.currActivity
            setTimeout(function () {
              that.openDiagram(res.result.processDef)
            }, 500)
            that.height = (res.result.height > 100 ? res.result.height : 100) + 'px'
          } else {
            that.messageUtil.warning(res.message)
          }
        }).finally(() => {
          that.spinning = false
        })
      },
      getHistActivity () {
        return this.histActivity
      },
      getCurrActivity () {
        return this.currActivity
      }
    },
    mounted () {
      // 获取到属性ref为“content”的dom节点
      this.container = this.$refs.content
      // 获取到属性ref为“canvas”的dom节点
      this.canvas = this.$refs.canvas

      // 建模，官方文档这里讲的很详细
      this.viewer = new NavigatedViewer({
        container: this.canvas,
        height: '100%'
      })
      this.open()
    },
    destroyed () {
      this.histActivity = {}
      this.currActivity = {}
    },
    watch: {
      refreshFlg (value) {
        if (value > 1) {
          this.open()
        }
      }
    }
  }
</script>

<style scoped lang="less">
  @import '~@yuncheng/ych-bpm-designer/styles/bpmn-js/assets/diagram-js.css';
</style>
